package com.leemon.mall.security.permission;

import com.leemon.mall.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;

import java.util.Collection;

/**
 * @author limenglong
 * @create 2019-09-24 14:27
 * @desc 接口权限判断工具
 **/
@Component("permission")
public class PermissionService {

    /**
     * 判断接口是否有xxx权限
     *
     * @param permission xxx权限
     * @return Boolean
     */
    public boolean hasPermission(String permission) {
        if (StringUtils.isBlank(permission)) {
            return false;
        }
        Authentication authentication = SecurityUtils.getAuthentication();
        if (authentication == null) {
            return false;
        }


        return authentication
                .getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .filter(StringUtils::isNotBlank)
                .anyMatch(authStr -> PatternMatchUtils.simpleMatch(permission,authStr));
    }

}
